package com.manager.seat.security;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @ClassName AuthInterceptor
 * @Description TODO
 * @date 2022/10/29 10:52
 * @Version 1.0
 */
@Slf4j
@Component
public class AuthInterceptor implements HandlerInterceptor {
    @Autowired
    private RequestHeaderContext requestHeaderContext;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 拦截处理代码
        //静态资源不被拦截器拦截
        String uri = request.getRequestURI();
        boolean flag = uri.contains("/user/manager") || uri.contains("image/manage");
        //设置过滤不拦截
        if (!flag) {
            if (uri.endsWith("js") || uri.endsWith("css") || uri.endsWith("jpg") || uri.endsWith("svg") || uri.endsWith("jpg") || uri.endsWith("png")) {
                return true;
            }
            HttpSession session = request.getSession();
            // 获取用户信息，如果没有用户信息直接返回提示信息
            String userId = (String) session.getAttribute("userId");
            String userName = (String) session.getAttribute("userName");
            requestHeaderContext.setUserId(userId);
            requestHeaderContext.setUserName(userName);
            if (userId == null) {
                request.setAttribute("msg", "请先登录！");
                //request.getRequestDispatcher("logging").forward(request, response);
                return true;
            } else {

            }
        }

        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 拦截处理代码
        //静态资源不被拦截器拦截
        // String uri = request.getRequestURI();
        //HttpSession session = request.getSession();
        // 获取用户信息，如果没有用户信息直接返回提示信息
        //String userInfo = (String) session.getAttribute("userId");


    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

}
